package com.he1618;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;

public class CpuInfoReader {

    public static void main(String[] args) {
        OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();

        // 获取 CPU 数量
        int availableProcessors = osBean.getAvailableProcessors();
        System.out.println("Number of processors: " + availableProcessors);

        // 获取系统负载
        double systemLoadAverage = osBean.getSystemLoadAverage();
        System.out.println("System load average: " + systemLoadAverage);

        // 获取 CPU 使用率
        double cpuUsage = getProcessCpuLoad();
        System.out.println("CPU usage: " + cpuUsage + "%");
    }

    private static double getProcessCpuLoad() {
        OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
        if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
            com.sun.management.OperatingSystemMXBean sunOsBean =
                    (com.sun.management.OperatingSystemMXBean) osBean;
            return sunOsBean.getProcessCpuLoad() * 100;
        } else {
            // Not supported on this platform
            return -1;
        }
    }
}
